// 处理流式响应
/**
 * Handles streaming response for Server-Sent Events (SSE).
 * Sets appropriate headers and streams chunks from the response in SSE format.
 * Automatically sends "[DONE]" event when streaming completes or error message if failed.
 *
 * @async
 * @function handleStreamResponse
 * @param {Object} response - The source stream to read chunks from
 * @param {Object} res - The HTTP response object to write SSE data to
 */
async function handleStreamResponse(response, res) {
    res.setHeader("Content-Type", "text/event-stream");
    res.setHeader("Cache-Control", "no-cache");
    res.setHeader("Connection", "keep-alive");

    try {
        for await (const chunk of response) {
            // console.log("chunk", chunk);
            res.write(`data: ${JSON.stringify(chunk)}\n\n`); // SSE 格式
        }
        res.write("data: [DONE]\n\n");
        res.end();
    } catch (error) {
        res.write(`data: ${JSON.stringify({ error: error.message })}\n\n`);
        res.end();
    }
}

module.exports = handleStreamResponse;
